package com.strongbj.iot.devices.reader.request.handle;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;

import java.net.InetSocketAddress;
import java.util.List;

import com.strongbj.core.message.IMessageHandle;
import com.strongbj.iot.devices.reader.message.ReaderMessageFactory;
import com.strongbj.iot.devices.reader.request.entity.ReaderCollectionTimeEntity;
import com.strongbj.iot.devices.reader.request.message.MQMessage;
import com.strongbj.iot.devices.reader.request.message.MQMessageData;
import com.strongbj.iot.devices.reader.server.ReaderServer;

/**
 * 启动基站主动上传的处理类
 * @author yuzhantao
 *
 */
public class InitiateBaseStationActiveUploadHandle implements IMessageHandle<MQMessage<Object>,Object> {
	private final static String ACTION_CODE = "collect002";
	private ReaderMessageFactory rmFactory=new ReaderMessageFactory();
	
	@Override
	public boolean isHandle(MQMessage<Object> t) {
		if(t.getActionCode().equals(ACTION_CODE)){
			return true;
		}else{
			return false;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public Object handle(ChannelHandlerContext ctx, MQMessage<Object> t) {
		for(MQMessageData<ReaderCollectionTimeEntity> data:(List<MQMessageData<ReaderCollectionTimeEntity>>)t.getAwsPostData()){
			for (io.netty.channel.Channel c : ReaderServer.channels) {
				InetSocketAddress insocket = (InetSocketAddress)c.remoteAddress();
				if(data.getDevIp().equals(insocket.getAddress().getHostAddress())){
					ByteBuf bs;
					try {
						bs = Unpooled.copiedBuffer(this.messageDataToBytes(data));
			            c.writeAndFlush(bs);
					} catch (Exception e) {
						e.printStackTrace();
					}
		            break;
				}
			}
        }
		return null;
	}
	
	// mq消息转byte数组
	private byte[] messageDataToBytes(MQMessageData<ReaderCollectionTimeEntity> data) throws Exception{
		return rmFactory.createReaderMessage(
				data.getDevAddrCode(), 
				(byte)2, 
				new byte[]{data.getDatas().getReaderTime()});
	}

}
